package de.koller.rRender.convert;

import de.koller.oceanFramework.util.ColorIntUtil;
import de.koller.rRender.szene.IGenerate;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Convert {

	private final IGenerate generate;
	private RenderFrame[] curr;
	private RenderFrame[] melt;
	private RenderFrame frame;
	private boolean firstMelt = false;
	
	public Convert( IGenerate generate, int frames ) {
		this.generate = generate;
		this.curr = new RenderFrame[ frames ];
		this.melt = new RenderFrame[ frames ];
	}
	
	public void melt( int vid ) {
		if( !firstMelt ) {
			for( int i = 0; i < curr.length; i++ )
				curr[i] = renderFrame();
			for( int i = 0; i < melt.length; i++ )
				melt[i] = renderFrame();
			firstMelt = true;
		}
		
		curr = melt;
		melt = new RenderFrame[ curr.length ];
		for( int i = 0; i < melt.length; i++ )
			melt[i] = renderFrame();
		
		try {
			frame = combine();
			ImageIO.write( frame, "png", new File( "./output/" + vid + ".png" ) );
		} catch( IOException ex ) {
			System.err.println( ex );
		}
	}

	private RenderFrame combine() {
		RenderFrame f = new RenderFrame();
		
		for( int x = 0; x < f.getWidth(); x++ )
			for( int y = 0; y < f.getHeight(); y++ ) {
				int a = 0;
				int r = 0;
				int g = 0;
				int b = 0;
				
				for( int i = 0; i < curr.length; i++ ) {
					int c = curr[i].getRGB( x, y );
					a += ColorIntUtil.getAValue( c );
					r += ColorIntUtil.getRValue( c );
					g += ColorIntUtil.getGValue( c );
					b += ColorIntUtil.getBValue( c );
				}
				
				for( int i = 0; i < melt.length; i++ ) {
					int c = melt[i].getRGB( x, y );
					a += ColorIntUtil.getAValue( c );
					r += ColorIntUtil.getRValue( c );
					g += ColorIntUtil.getGValue( c );
					b += ColorIntUtil.getBValue( c );
				}
				
				a /= curr.length + melt.length;
				r /= curr.length + melt.length;
				g /= curr.length + melt.length;
				b /= curr.length + melt.length;
				
				f.setRGB( x, y, ColorIntUtil.getIntColor( a, r, g, b ) );
			}
		
		return f;
	}
	
	private RenderFrame renderFrame() {
		RenderFrame f = new RenderFrame();
		generate.generateFrame( f );
		return f;
	}

	public RenderFrame getFrame() {
		return frame;
	}
	
}
